package servlet;

import entity.RatifyLesson;
import service.LessonService;
import service.RatifyLessonService;
import service.impl.LessonServiceImpl;
import service.impl.RatifyLessonServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/lessonUpdateStatusServlet")
public class LessonUpdateStatusServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String lessoncode = request.getParameter("code");
        String status = request.getParameter("status");
        String lessonname = request.getParameter("name");
        String teacher = request.getParameter("teacher");
        int ifratify = 0;
        String student = String.valueOf(request.getSession().getAttribute("username"));
        String code = String.valueOf((int)(Math.random()*100000000));
        System.out.println(code);
        RatifyLesson rlesson = new RatifyLesson(code,lessoncode,student,lessonname,teacher,ifratify,null,null);
        LessonService service = new LessonServiceImpl();
        RatifyLessonService rservice = new RatifyLessonServiceImpl();
        try {
            rservice.addordelete(rlesson,status);
            service.disapprove(lessoncode,student,"");
            rservice.disapprove(lessoncode,student,"");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        boolean flag = true;

        HttpSession session = request.getSession();
        session.setAttribute("student",student);
        session.setAttribute("lessoncode",lessoncode);

        try {
            service.updatestatus(lessoncode,student,status,flag);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        int statusint = Integer.valueOf(status);

        try {
            service.apply(lessoncode,student,"");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(statusint==0) {
            response.sendRedirect("/apply.html");
        }else{
            response.sendRedirect("/lessonListServlet");
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }
}
